package com.dongjiantong.app.controller.farmrecords.retailRecords;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongjiantong.biz.service.FarmStockService;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.model.Response;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.common.web.util.UserUtil;
import com.dongjiantong.farmrecords.enums.FarmRecordsNumberStatus;
import com.dongjiantong.farmrecords.model.FarmRecordsRetailProduction;
import com.dongjiantong.farmrecords.service.FarmRecordsRetailProductionService;
import com.dongjiantong.openplatform.annotations.OpenBean;
import com.dongjiantong.openplatform.annotations.OpenMethod;
import com.dongjiantong.sys.service.AnimalTypeService;
import com.dongjiantong.user.enums.FarmsEnum;
import com.dongjiantong.user.model.Farms;
import com.dongjiantong.user.service.FarmsService;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 散户养殖档案-生产记录
 * @author Lee
 * @date 2018/1/8
 */
@Slf4j
@OpenBean
public class FarmRecordsRetailProductionController {
    @Reference(version = "1.0.0")
    public FarmRecordsRetailProductionService farmRecordsRetailProductionService;
    @Reference(version = "1.0.3")
    public AnimalTypeService animalTypeService;
    @Reference(version = "1.0.0")
    public FarmStockService farmStockService;
    @Reference(version = "1.0.0")
    public FarmsService farmsService;

    /**
     * (政府端)
     * 根据养殖场id,起止时间或者状态查询散户生产记录 (条件都可以为空,表示查询所有)
     * @param farmId  请求的养殖场id
     * @param fromDate 请求的查询开始时间
     * @param toDate   请求的查询结束时间
     * @param pageNum
     * @param pageSize
     * @param breedSecondType   请求的畜种
     * @return  Response<PageInfo<farmrecordsRetailProduction>>
     */
    @OpenMethod(key = "app.farmrecords.retail.farmrecordsRetailProduction.selectByFarmIdAndDate",
            paramNames = {"farmId","fromDate","toDate","pageNum","pageSize","breedSecondType"},
            httpMethods = RequestMethod.GET)
    public Response<PageInfo<FarmRecordsRetailProduction>> selectByFarmIdAndDate(@RequestParam(required = false) Long farmId,
                                                                                 @RequestParam(required = false) String fromDate,
                                                                                 @RequestParam(required = false) String toDate,
                                                                                 @RequestParam(required = false) Integer pageNum,
                                                                                 @RequestParam(required = false) Integer pageSize,
                                                                                 @RequestParam(required = false) Integer breedSecondType){
        if (farmRecordsRetailProductionService == null){
            throw new OPServerException("请检查 farmRecordsRetailProductionService 服务");
        }

        Map map = Maps.newHashMap();
        Long userId = UserUtil.getUserId();
        map.put("userId",userId);

        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 20;
        }

        if (farmId != null){
            //如果养殖场id不为空,则根据养殖场id查询
            map.put("farm_id",farmId);
        }

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (!Strings.isNullOrEmpty(fromDate)){
                Date startDate = sdf.parse(fromDate);
                map.put("startDate",startDate);
            }
            if (!Strings.isNullOrEmpty(toDate)){
                Date endDate = sdf.parse(toDate);
                map.put("endDate",endDate);
            }
        } catch (Exception e){
            log.error(e.getMessage());
        }

        map.put("farmsType", FarmsEnum.Retail.getCode());

        map.put("status", FarmRecordsNumberStatus.SUBMIT.getCode());

        if (breedSecondType != null) {
            map.put("breed_second_type",breedSecondType);
        }

        PageInfo<FarmRecordsRetailProduction> farmRecordsRetailProductionPageInfo = farmRecordsRetailProductionService.selectByMap(pageNum,pageSize,map);
        return Response.ok(farmRecordsRetailProductionPageInfo);
    }

    /**
     * (养殖端)
     * 根据提交状态分页查询列表
     * @param farmId
     * @param status
     * @return
     */
    @OpenMethod(key = "app.farmrecords.retail.farmRecordsRetailProduction.selectListByStatus",
            paramNames = {"farmId","status","pageSize","pageNum"},
            httpMethods = RequestMethod.GET)
    public Response<PageInfo<FarmRecordsRetailProduction>> selectListByStatus(@RequestParam(required = false) Long farmId,
                                                                        @RequestParam(required = false) Integer status,
                                                                        @RequestParam(required = false) Integer pageSize,
                                                                        @RequestParam(required = false) Integer pageNum){
        if (farmRecordsRetailProductionService == null){
            throw new OPServerException("farmRecordsRetailProductionService 服务为空,请重启服务后重试");
        }
        if (farmId == null){
            throw new OPServerException("养殖场id不能为空,请检查后重试");
        }

        if (pageSize == null){
            pageSize = 20;
        }
        if (pageNum == null){
            pageNum = 1;
        }

        PageInfo<FarmRecordsRetailProduction> farmRecordsRetailProductionPageInfo = farmRecordsRetailProductionService.selectListByStatus(pageNum,pageSize,status,farmId);

        return Response.ok(farmRecordsRetailProductionPageInfo);
    }

    /**
     * 根据主键id查询对应生产记录
     * @param id
     * @return
     */
    @OpenMethod(key = "app.farmrecords.retail.farmRecordsRetailProduction.selectById",
            paramNames = {"id"},
            httpMethods = RequestMethod.GET)
    public Response<FarmRecordsRetailProduction> selectById(@RequestParam(required = false)Long id){
        if (id == null) {
            throw new OPServerException(HttpCode.BAD_REQUEST, "请求的id不能为空");
        }
        try {
            if (farmRecordsRetailProductionService == null){
                throw new OPServerException("farmRecordsProductionService 为null,请检查");
            }

            FarmRecordsRetailProduction farmRecordsRetailProduction = farmRecordsRetailProductionService.selectByPrimaryKey(id);
            if (farmRecordsRetailProduction == null){
                return Response.fail(HttpCode.INTERNAL_SERVER_ERROR,"查无数据");
            }
            return Response.ok(farmRecordsRetailProduction);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 新增一条生产记录 (直接暂存 或者 直接提交)
     * @param farmRecordsRetailProduction
     * @param toStatus 单据状态
     * @return
     */
    @OpenMethod(key = "app.farmrecords.retail.farmRecordsRetailProduction.createOne",
            paramNames = {"farmRecordsRetailProduction","toStatus","isFrom"},
            httpMethods = RequestMethod.POST)
    public Response<Map<String,Object>> createOne(@RequestBody(required = false) FarmRecordsRetailProduction farmRecordsRetailProduction,
                                                  @RequestParam(required = false) Integer toStatus,
                                                  @RequestParam(required = false) Integer isFrom){
        if (farmRecordsRetailProduction == null) {
            throw new OPServerException(HttpCode.BAD_REQUEST, "请求参数对象不能为空");
        }
        if (farmRecordsRetailProductionService == null){
            throw new OPServerException("farmRecordsRetailProductionService 为null,请检查");
        }

        //获取登陆人信息
        LoginInfo loginInfo = UserUtil.getCurrentUser();

        Long id = farmRecordsRetailProductionService.createOne(loginInfo,farmRecordsRetailProduction, toStatus,isFrom);

        Map<String,Object> result = Maps.newHashMap();
        result.put("receiptId",id);

        return Response.ok(result);
    }

    /**
     * 根据id或者number 更新一条单据信息
     * @param farmRecordsRetailProduction 请求的对象
     * @param toStatus
     * @return  boolean (更新成功返回true 反之返回false)
     */
    @OpenMethod(key = "app.farmrecords.retail.farmRecordsRetailProduction.updateByIdOrNumber",
            paramNames = {"farmRecordsProduction","toStatus"},
            httpMethods = RequestMethod.POST)
    public Response<Map<String,Object>> updateByIdOrNumber(@RequestBody (required = false) FarmRecordsRetailProduction farmRecordsRetailProduction,
                                                           @RequestParam(required = false) Integer toStatus){
        if (farmRecordsRetailProduction == null){
            throw new OPServerException(HttpCode.BAD_REQUEST,"请求参数对象不能为空");
        }else{
            if (farmRecordsRetailProductionService == null){
                throw new OPServerException("farmRecordsRetailProductionService 为null,请检查");
            }
            if (farmRecordsRetailProduction.getId() == null){
                throw new OPServerException(HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST,HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getMessage());
            }
            Integer con = farmRecordsRetailProductionService.updateByIdOrNumber(farmRecordsRetailProduction,toStatus);

            Map<String,Object> map = Maps.newHashMap();
            if (con == 1) {
                map.put("updateResult","true");
            }else {
                map.put("updateResult","false");
            }

            return Response.ok(map);
        }
    }

    /**
     * (政府端)
     * 根据养殖场id 动物畜种查询存栏变动数合计
     * @param farmId
     * @param breedSecondType
     */
    @OpenMethod(key = "app.farmrecords.retail.farmRecordsRetailProduction.selectQuantityChangeGov",
            paramNames = {"farmId","breedSecondType"},
            httpMethods = RequestMethod.GET)
    public Response<Object> selectQuantityChangeGov(@RequestParam(required = false) Long farmId,
                                                    @RequestParam(required = false) Integer breedSecondType){
        if (animalTypeService == null) {
            throw new OPServerException("animalTypeService 服务为空,请重启后重试");
        }
        if (farmRecordsRetailProductionService == null) {
            throw new OPServerException("farmRecordsRetailProductionService 服务为空,请重启后重试");
        }

        Long userId = UserUtil.getUserId();

        Map<String,Object> result = Maps.newHashMap();
        List<Map<String,Object>> list = Lists.newArrayList();

        if (farmId != null) {
            //如果传入养殖场id 则养殖畜种已经确定
            Farms farms = farmsService.getFarmsById(farmId);
            Integer animalCode = null;
            if (farms != null) {
                animalCode = farms.getAnimalTwoType();
            }

            Integer quantity = farmRecordsRetailProductionService.selectQuantityChangeByFarmId(farmId,animalCode);
            if (quantity == null){
                quantity = 0;
            }

            result.put("animalCode",animalCode);
            result.put("stock",quantity);
            list.add(result);
        }else {
            //反之 根据畜种查询
            if (breedSecondType != null) {
                Integer quantity = farmRecordsRetailProductionService.selectQuantityChangeByGovAndBreedType(userId,breedSecondType);

                result.put("animalCode",breedSecondType);
                result.put("stock",quantity);
                list.add(result);
            }else {
                //畜种和养殖场id都无参 根据登陆人获取其管辖区域所有已经养殖的养殖品种
                List<Integer> animalCodeList = farmsService.selectFarmBreedTypeByGovUserId(userId);

                if (animalCodeList.size() > 0){
                    for (Integer code : animalCodeList){
                        Map<String,Object> result1 = Maps.newHashMap();
                        Integer quantity = farmRecordsRetailProductionService.selectQuantityChangeByGovAndBreedType(userId,code);

                        /*
                        //去除牛?
                        if (AnimalTypeEnum.BULL.getCode().equals(code)){
                            result1.put("animalCode",code);
                            result1.put("stock",quantity);
                            list.add(result1);
                        }*/

                        result1.put("animalCode",code);
                        result1.put("stock",quantity);
                        list.add(result1);
                    }
                }
            }
        }

        return Response.ok(list);
    }

    /**
     * (养殖端)
     * 根据养殖场id查询的存栏变动数合计
     * 养殖场三级畜种分类统计
     * @param farmId
     *//*
    @OpenMethod(key = "app.farmrecords.retail.farmrecordsproduction.selectQuantityChangeByFarmId.thirdAnimalType",
            paramNames = {"farmId"},
            httpMethods = RequestMethod.GET)
    public Response<Object> selectThirdQuantityChangeByFarmId(@RequestParam(required = false) Long farmId){

        if (farmId == null){
            throw new OPServerException("养殖场id为空,请检查后重试");
        }

        //先根据养殖场二级畜种查询三级畜种
        Farms farms = farmsService.getFarmsById(farmId);
        List<Integer> animalTypeList = null;
        if (farms != null){
            animalTypeList = animalTypeService.queryChildCode(farms.getAnimalTwoType().toString());
        }

        //返回三级畜种对应的合计总数
        List<Map<String,Integer>> list = Lists.newArrayList();

        for (Integer animalThirdType : animalTypeList){
            Map<String,Integer> result = Maps.newHashMap();
            Integer changeQuantity = farmRecordsRetailProductionService.selectQuantityChangeByFarmId(farmId,null,animalThirdType);
            if (changeQuantity == null){
                changeQuantity = 0;
            }
            result.put("animalCode",animalThirdType);
            result.put("stock",changeQuantity);
            list.add(result);
        }

        return Response.ok(list);
    }*/

    /**
     * (养殖端)
     * 根据养殖场id查询的存栏变动数合计
     * 养殖场二级畜种分类统计
     * @param farmId
     */
    @OpenMethod(key = "app.farmrecords.retail.farmrecordsproduction.selectQuantityChangeByFarmId.secondAnimalType",
            paramNames = {"farmId"},
            httpMethods = RequestMethod.GET)
    public Response<Object> selectSecondQuantityChangeByFarmId(@RequestParam(required = false) Long farmId){

        if (farmId == null){
            throw new OPServerException("养殖场id为空,请检查后重试");
        }

        //先根据养殖场查询二级畜种
        Farms farms = farmsService.getFarmsById(farmId);
        Integer changeQuantity = farmRecordsRetailProductionService.selectQuantityChangeByFarmId(farmId,farms.getAnimalTwoType());
        if (changeQuantity == null){
            changeQuantity = 0;
        }

        Map<String,Integer> result = Maps.newHashMap();
        result.put("stock",changeQuantity);

        return Response.ok(result);
    }
}
